package com.yitongmao.common;

import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteReadOnlyDatabaseException;
import android.os.Build;

import com.yitongmao.common.reminder.ReaderApplication;
import com.yitongmao.common.sharesdk.Account;
import com.yitongmao.common.sharesdk.ArticalDraftBean;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.util.Loger;
import com.yitongmao.yitmfruit.R;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaowei on 16/9/5.
 */
public class LocalArticalDraftDbHelper extends SQLiteOpenHelper {

    public ACache mCache = ACache.get(ReaderApplication.applicationContext);

    // Database name
    private static final String DATABASE_NAME = ReaderApplication.getInstace().getResources().getString(R.string.auth_cancle) + "_local_artical_draft_db";
    // Database version aligned if possible to software version
    private static final int DATABASE_VERSION = 1;

    // Notes table name
    private static final String TABLE_LIVING = "create table " + DATABASE_NAME +
            "(save_uid varchar(100),save_key varchar(100),created_time varchar(100))";

    // Notes table columns
    private static final String KEY_ID = "creation";
    private static final String KEY_SAVE_UID = "save_uid";//
    private static final String KEY_SAVE_KEY = "save_key";//key= "artical_draft_time"
    private static final String KEY_CREATED_TIME = "created_time";

    private final Context mContext;
    private static LocalArticalDraftDbHelper instance = null;
    private SQLiteDatabase db;

    public static synchronized LocalArticalDraftDbHelper getInstance() {
        return getInstance(ReaderApplication.getInstace().getApplicationContext());
    }

    public static synchronized LocalArticalDraftDbHelper getInstance(Context context) {
        if (instance == null) {
            instance = new LocalArticalDraftDbHelper(context);
        }
        return instance;
    }

    private LocalArticalDraftDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.mContext = context;
    }

    private SQLiteDatabase getDatabase() {
        return getDatabase(false);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private SQLiteDatabase getDatabase(boolean forceWritable) {
        try {
            SQLiteDatabase db = getReadableDatabase();
            if (forceWritable && db.isReadOnly()) {
                throw new SQLiteReadOnlyDatabaseException("Required writable database, obtained read-only");
            }
            return db;
        } catch (IllegalStateException e) {
            return this.db;
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //建表
        Loger.i("ReminderDbHelper-onCreate", "Database creation");
        db.execSQL(TABLE_LIVING);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    @TargetApi(Build.VERSION_CODES.FROYO)
    public void insertArticalDraft(ArticalDraftBean articalDraftBean) {
        SQLiteDatabase db = getDatabase();
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(KEY_SAVE_UID, getAccountUid());
        values.put(KEY_SAVE_KEY, articalDraftBean.getArticalDraftSaveKey());
        values.put(KEY_CREATED_TIME, articalDraftBean.getArticalDraftSaveTime());

        if (getArticalDraft(articalDraftBean.getArticalDraftSaveKey(), getAccountUid()) != null) {
            Loger.i("insertArticalDraft", "insertArticalDraft-delete:" + articalDraftBean.getArticalDraftSaveKey());
            deleteArticalDraft(articalDraftBean, getAccountUid());
        }

        db.insertWithOnConflict(DATABASE_NAME, KEY_ID, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    public ArticalDraftBean getArticalDraft(String saveKey, String uid) {
        ArticalDraftBean articalDraftBean = new ArticalDraftBean();
        String whereCondition = " WHERE " + KEY_SAVE_KEY + " = " + "'" + saveKey + "'" + " AND " + KEY_SAVE_UID + " = " + "'" + uid + "'";
        String query = "SELECT * FROM " + DATABASE_NAME + whereCondition;
        Cursor cursor = null;
        try {
            cursor = getDatabase().rawQuery(query, null);

            if (cursor != null && cursor.moveToFirst()) {
                articalDraftBean.setArticalDraftSaveKey(cursor.getString(cursor.getColumnIndex(KEY_SAVE_KEY)));
                articalDraftBean.setArticalDraftSaveTime(cursor.getString(cursor.getColumnIndex(KEY_CREATED_TIME)));
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        Loger.v("getNotes", "Query: Retrieval finished!");
        return articalDraftBean;
    }

    public List<ArticalDraftBean> getArticalDrafts(String uid) {
        String whereCondition = " WHERE " + KEY_SAVE_UID + " = " + "'" + uid + "'" + " AND " + KEY_SAVE_KEY + " IS NOT NULL";
        List<ArticalDraftBean> articalDraftBeanList = new ArrayList<>();

        String query = "SELECT " + KEY_SAVE_KEY + "," + KEY_CREATED_TIME + " FROM " + DATABASE_NAME + whereCondition;

        Cursor cursor = null;
        try {
            cursor = getDatabase().rawQuery(query, null);

            if (cursor != null && cursor.getCount() > 0) {
                if (cursor.moveToFirst()) {
                    do {
                        int i = 0;
                        ArticalDraftBean articalDraftBean = new ArticalDraftBean();
                        articalDraftBean.setArticalDraftSaveKey(cursor.getString(i++));
                        articalDraftBean.setArticalDraftSaveTime(cursor.getString(i++));
                        articalDraftBeanList.add(articalDraftBean);

                    } while (cursor.moveToNext());
                }
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        Loger.v("getNotes", "Query: Retrieval finished!");
        return articalDraftBeanList;
    }

    private boolean deleteArticalDraft(ArticalDraftBean articalDraftBean, String uid) {
        int deletedNotes;
        SQLiteDatabase db = getDatabase(true);
        deletedNotes = db.delete(DATABASE_NAME, KEY_SAVE_KEY + " = ? and " + KEY_SAVE_UID + " = ?", new String[]{String.valueOf(articalDraftBean.getArticalDraftSaveKey()),uid});
        if (deletedNotes == 1) {
            if (mCache.remove(articalDraftBean.getArticalDraftSaveKey())) {
                return true;
            }
        }
        return false;
    }

    public boolean deleteArticalDraftSaveKey(String articalDraftSaveKey, String uid) {
        int deletedNotes;
        SQLiteDatabase db = getDatabase(true);
        deletedNotes = db.delete(DATABASE_NAME, KEY_SAVE_KEY + " = ? and " + KEY_SAVE_UID + " = ?", new String[]{String.valueOf(articalDraftSaveKey),uid});
        if (deletedNotes == 1) {
            if (mCache.remove(articalDraftSaveKey)) {
                return true;
            }
        }
        return false;
    }

    //获取账户信息
    public String getAccountUid() {
        Account account = null;
        String uid = null;
        String account_str = mCache.getAsString(AppConstants.memberCenter.KEY_CACHE_MY_LOGIN);
        Loger.i("LocalArticalDraftDbHelper", "LocalArticalDraftDbHelper-getAccountInfo-" + account_str);
        if (account_str != null && !account_str.trim().equals("")) {
            account = Account.objectFromData(account_str);
            if (account != null) {
                uid = account.getUid() + "";
            }
        }
        return uid;
    }

}
